// pages/bluetooth-detect/bluetooth-detect.js
const app = getApp()

Page({
  data: {
    // 蓝牙扫描数据
    isScanning: false,
    scanStartTime: null,
    scanDuration: 0,
    
    // 设备列表
    bluetoothDevices: [],
    suspiciousDevices: [],
    totalDevices: 0,
    
    // 蓝牙状态
    bluetoothAvailable: false,
    bluetoothEnabled: false,
    
    // 界面控制
    showGuide: false,
    showSettings: false,
    showDetail: false,
    selectedDevice: null,
    
    // 检测设置
    maxScanDuration: 30, // 最大扫描时长（秒）
    vibrationEnabled: true,
    soundEnabled: false,
    
    // 可疑设备关键词
    suspiciousKeywords: [
      'camera', 'cam', 'spy', 'hidden', 'recorder',
      'monitor', 'surveillance', 'mic', 'audio',
      'video', 'dvr', 'nvr', 'security', 'watch'
    ]
  },

  onLoad() {
    console.log('蓝牙设备扫描页面加载')
    this.checkBluetoothAvailability()
    this.loadSettings()
  },

  onShow() {
    wx.setKeepScreenOn({
      keepScreenOn: true
    })
  },

  onHide() {
    this.stopScan()
  },

  onUnload() {
    this.cleanup()
  },

  // 页面清理
  cleanup() {
    this.stopScan()
    this.closeBluetoothAdapter()
    wx.setKeepScreenOn({
      keepScreenOn: false
    })
  },

  // 检查蓝牙可用性
  checkBluetoothAvailability() {
    wx.getSystemInfo({
      success: (res) => {
        console.log('设备信息:', res.platform)
        this.setData({
          bluetoothAvailable: true
        })
        // 初始化蓝牙适配器
        this.initBluetoothAdapter()
      },
      fail: (err) => {
        console.error('获取设备信息失败:', err)
        this.setData({
          bluetoothAvailable: false
        })
      }
    })
  },

  // 初始化蓝牙适配器
  initBluetoothAdapter() {
    wx.openBluetoothAdapter({
      success: (res) => {
        console.log('蓝牙适配器初始化成功')
        this.setData({
          bluetoothEnabled: true
        })
        this.getBluetoothAdapterState()
      },
      fail: (err) => {
        console.log('蓝牙适配器初始化失败:', err)
        this.setData({
          bluetoothEnabled: false
        })
        
        if (err.errCode === 10001) {
          wx.showModal({
            title: '蓝牙未开启',
            content: '请开启手机蓝牙后重试',
            showCancel: false
          })
        }
      }
    })
  },

  // 获取蓝牙适配器状态
  getBluetoothAdapterState() {
    wx.getBluetoothAdapterState({
      success: (res) => {
        console.log('蓝牙适配器状态:', res)
        this.setData({
          bluetoothEnabled: res.available
        })
      }
    })
  },

  // 开始扫描
  startScan() {
    if (!this.data.bluetoothEnabled) {
      wx.showModal({
        title: '蓝牙不可用',
        content: '请确保手机蓝牙已开启',
        showCancel: false
      })
      return
    }

    this.setData({
      isScanning: true,
      scanStartTime: Date.now(),
      scanDuration: 0,
      bluetoothDevices: [],
      suspiciousDevices: [],
      totalDevices: 0
    })

    // 开始扫描蓝牙设备
    wx.startBluetoothDevicesDiscovery({
      allowDuplicatesKey: false,
      success: (res) => {
        console.log('开始扫描蓝牙设备')
        this.startScanTimer()
        this.onBluetoothDeviceFound()
      },
      fail: (err) => {
        console.error('开始扫描失败:', err)
        this.setData({
          isScanning: false
        })
        wx.showToast({
          title: '扫描启动失败',
          icon: 'error'
        })
      }
    })
  },

  // 启动扫描计时器
  startScanTimer() {
    this.scanTimer = setInterval(() => {
      if (!this.data.isScanning) return
      
      const elapsed = Math.floor((Date.now() - this.data.scanStartTime) / 1000)
      this.setData({
        scanDuration: elapsed
      })
      
      // 自动停止扫描
      if (elapsed >= this.data.maxScanDuration) {
        this.stopScan()
      }
    }, 1000)
  },

  // 监听蓝牙设备发现
  onBluetoothDeviceFound() {
    wx.onBluetoothDeviceFound((res) => {
      const devices = res.devices || []
      
      devices.forEach(device => {
        // 过滤掉没有名称的设备
        if (!device.name && !device.localName) return
        
        const deviceName = device.name || device.localName || '未知设备'
        const deviceId = device.deviceId
        
        // 检查是否已存在
        const existingIndex = this.data.bluetoothDevices.findIndex(d => d.deviceId === deviceId)
        
        const deviceInfo = {
          deviceId: deviceId,
          name: deviceName,
          RSSI: device.RSSI || -100,
          advertisData: device.advertisData,
          serviceUUIDs: device.serviceUUIDs || [],
          isSuspicious: this.checkSuspiciousDevice(deviceName),
          suspiciousReason: this.getSuspiciousReason(deviceName),
          signalStrength: this.calculateSignalStrength(device.RSSI || -100)
        }
        
        if (existingIndex >= 0) {
          // 更新现有设备
          this.data.bluetoothDevices[existingIndex] = deviceInfo
        } else {
          // 添加新设备
          this.data.bluetoothDevices.push(deviceInfo)
        }
      })
      
      // 筛选可疑设备
      const suspiciousDevices = this.data.bluetoothDevices.filter(device => device.isSuspicious)
      
      this.setData({
        bluetoothDevices: this.data.bluetoothDevices,
        suspiciousDevices: suspiciousDevices,
        totalDevices: this.data.bluetoothDevices.length
      })
      
      // 发现可疑设备时震动提醒
      if (suspiciousDevices.length > 0 && this.data.vibrationEnabled) {
        wx.vibrateShort()
      }
    })
  },

  // 检查可疑设备
  checkSuspiciousDevice(deviceName) {
    if (!deviceName) return false
    
    const name = deviceName.toLowerCase()
    
    // 检查关键词
    for (const keyword of this.data.suspiciousKeywords) {
      if (name.includes(keyword)) {
        return true
      }
    }
    
    // 检查模式匹配（使用字符串匹配而不是正则表达式）
    const patterns = [
      { pattern: 'cam', isPrefix: true },     // cam开头
      { pattern: 'ipcam', isPrefix: true },   // ipcam开头  
      { pattern: 'spy', isPrefix: true },     // spy开头
      { pattern: 'hidden', isPrefix: true },  // hidden开头
    ]
    
    for (const p of patterns) {
      if (p.isPrefix && name.startsWith(p.pattern)) {
        return true
      } else if (!p.isPrefix && name.includes(p.pattern)) {
        return true
      }
    }
    
    // 检查是否为6位随机字符（简单判断）
    if (deviceName.length === 6 && /^[A-Za-z0-9]{6}$/.test(deviceName)) {
      return true
    }
    
    // 检查是否为12位十六进制字符
    if (deviceName.length === 12 && /^[0-9A-Fa-f]{12}$/.test(deviceName)) {
      return true
    }
    
    return false
  },

  // 获取可疑原因
  getSuspiciousReason(deviceName) {
    if (!deviceName) return ''
    
    const name = deviceName.toLowerCase()
    
    // 检查关键词
    for (const keyword of this.data.suspiciousKeywords) {
      if (name.includes(keyword)) {
        return `设备名称包含可疑关键词: ${keyword}`
      }
    }
    
    // 检查模式匹配
    const patterns = [
      { pattern: 'cam', isPrefix: true },
      { pattern: 'ipcam', isPrefix: true },
      { pattern: 'spy', isPrefix: true },
      { pattern: 'hidden', isPrefix: true },
    ]
    
    for (const p of patterns) {
      if (p.isPrefix && name.startsWith(p.pattern)) {
        return `设备名称符合可疑模式: ${p.pattern}开头`
      }
    }
    
    // 检查随机字符模式
    if (deviceName.length === 6 && /^[A-Za-z0-9]{6}$/.test(deviceName)) {
      return '设备名称疑似6位随机字符'
    }
    
    if (deviceName.length === 12 && /^[0-9A-Fa-f]{12}$/.test(deviceName)) {
      return '设备名称疑似12位十六进制字符'
    }
    
    return ''
  },

  // 计算信号强度百分比
  calculateSignalStrength(rssi) {
    // RSSI转换为百分比 (-40dBm = 100%, -100dBm = 0%)
    const minRssi = -100
    const maxRssi = -40
    const percentage = Math.max(0, Math.min(100, 
      ((rssi - minRssi) / (maxRssi - minRssi)) * 100
    ))
    return Math.round(percentage)
  },

  // 停止扫描
  stopScan() {
    this.setData({
      isScanning: false
    })
    
    // 清理计时器
    if (this.scanTimer) {
      clearInterval(this.scanTimer)
      this.scanTimer = null
    }
    
    // 停止蓝牙扫描
    wx.stopBluetoothDevicesDiscovery({
      success: (res) => {
        console.log('停止蓝牙扫描成功')
      }
    })
    
    // 显示结果
    const suspiciousCount = this.data.suspiciousDevices.length
    if (suspiciousCount > 0) {
      wx.showModal({
        title: '发现可疑设备',
        content: `扫描完成，发现 ${suspiciousCount} 个可疑蓝牙设备，建议进一步检查。`,
        showCancel: false
      })
    } else {
      wx.showToast({
        title: `扫描完成，发现 ${this.data.totalDevices} 个设备`,
        icon: 'success'
      })
    }
  },

  // 显示设备详情
  showDeviceDetail(e) {
    const index = e.currentTarget.dataset.index
    const device = this.data.bluetoothDevices[index]
    
    this.setData({
      selectedDevice: device,
      showDetail: true
    })
  },

  // 关闭设备详情
  closeDeviceDetail() {
    this.setData({
      showDetail: false,
      selectedDevice: null
    })
  },

  // 关闭蓝牙适配器
  closeBluetoothAdapter() {
    wx.closeBluetoothAdapter({
      success: (res) => {
        console.log('关闭蓝牙适配器成功')
      }
    })
  },

  // 加载设置
  loadSettings() {
    const settings = app.utils.getUserSettings()
    this.setData({
      maxScanDuration: settings.bluetoothScanDuration || 30,
      vibrationEnabled: settings.vibrationEnabled !== false,
      soundEnabled: settings.soundEnabled || false
    })
  },

  // 保存结果
  saveResult() {
    if (!this.data.scanStartTime) {
      wx.showToast({
        title: '请先开始扫描',
        icon: 'error'
      })
      return
    }

    const result = {
      id: app.utils.generateId(),
      timestamp: Date.now(),
      location: '',
      detectType: 'bluetooth',
      result: {
        bluetooth: {
          totalDevices: this.data.totalDevices,
          suspiciousDevices: this.data.suspiciousDevices.map(device => ({
            name: device.name,
            deviceId: device.deviceId,
            reason: device.suspiciousReason,
            signalStrength: device.signalStrength,
            RSSI: device.RSSI
          })),
          scanDuration: this.data.scanDuration
        }
      },
      riskLevel: app.utils.assessRiskLevel({
        bluetooth: { suspiciousDevices: this.data.suspiciousDevices }
      }),
      notes: ''
    }

    // 保存到本地存储
    const history = wx.getStorageSync('detection_history') || []
    history.unshift(result)
    wx.setStorageSync('detection_history', history)

    wx.showModal({
      title: '保存成功',
      content: `扫描结果已保存\n蓝牙设备: ${this.data.totalDevices} 个\n可疑设备: ${this.data.suspiciousDevices.length} 个\n风险等级: ${result.riskLevel}`,
      showCancel: false,
      success: () => {
        wx.showModal({
          title: '查看历史',
          content: '是否跳转到历史记录页面？',
          success: (res) => {
            if (res.confirm) {
              wx.switchTab({
                url: '/pages/history/history'
              })
            }
          }
        })
      }
    })
  },

  // 切换指南面板
  toggleGuide() {
    this.setData({
      showGuide: !this.data.showGuide
    })
  },

  // 切换设置面板
  toggleSettings() {
    this.setData({
      showSettings: !this.data.showSettings
    })
  },

  // 扫描时长改变
  onScanDurationChange(e) {
    const duration = parseInt(e.detail.value)
    this.setData({ 
      maxScanDuration: duration
    })
  },

  // 震动提醒切换
  onVibrationToggle(e) {
    this.setData({
      vibrationEnabled: e.detail.value
    })
  },

  // 声音提醒切换
  onSoundToggle(e) {
    this.setData({
      soundEnabled: e.detail.value
    })
  },

  // 分享给好友
  onShareAppMessage() {
    const suspiciousCount = this.data.suspiciousDevices.length
    const totalCount = this.data.totalDevices
    
    return {
      title: suspiciousCount > 0 ? 
        `蓝牙扫描发现 ${suspiciousCount} 个可疑设备 - 安心住助手` : 
        `蓝牙扫描检测到 ${totalCount} 个设备 - 安心住助手`,
      desc: '扫描周围蓝牙设备，识别可疑的监控设备',
      path: '/pages/bluetooth-detect/bluetooth-detect'
    }
  },

  // 分享到朋友圈
  onShareTimeline() {
    return {
      title: '蓝牙设备扫描 - 安心住助手',
      query: 'tool=bluetooth'
    }
  }
})
